import tkinter as tk  
from tkinter import messagebox  
import json  
  
def load_tasks():  
    try:  
        with open('tasks.json', 'r') as file:  
            tasks = json.load(file)  
    except FileNotFoundError:  
        tasks = []  
    except json.JSONDecodeError:  
        tasks = []  
    return tasks  
  
def save_tasks(tasks):  
    with open('tasks.json', 'w') as file:  
        json.dump(tasks, file, indent=4)  
  
def add_task():  
    task_description = task_entry.get()  
    if task_description:  
        task = {'description': task_description, 'completed': False}  
        global tasks  # Use global variable to access tasks list  
        tasks.append(task)  
        save_tasks(tasks)  
        update_task_list()  
        task_entry.delete(0, tk.END)  
    else:  
        messagebox.showwarning("Warning", "Task description cannot be empty!")  
  
def update_task_list():  
    task_listbox.delete(0, tk.END)  
    for task in tasks:  
        status = "✓" if task['completed'] else "✗"  
        task_listbox.insert(tk.END, f"{status} {task['description']}")  
  
def complete_task():  
    try:  
        selected_index = task_listbox.curselection()[0]  
        tasks[selected_index]['completed'] = True  
        save_tasks(tasks)  
        update_task_list()  
    except IndexError:  
        messagebox.showwarning("Warning", "No task selected!")  
  
def delete_task():  
    try:  
        selected_index = task_listbox.curselection()[0]  
        del tasks[selected_index]  
        save_tasks(tasks)  
        update_task_list()  
    except IndexError:  
        messagebox.showwarning("Warning", "No task selected!")  
  
# Initialize the application  
root = tk.Tk()  
root.title("ToDo List")  
  
# Create global tasks list  
tasks = load_tasks()  
  
# Create widgets  
task_entry = tk.Entry(root, width=50)  
task_entry.grid(row=0, column=0, columnspan=2, padx=10, pady=10)  
  
add_button = tk.Button(root, text="Add Task", command=add_task)  
add_button.grid(row=0, column=2, padx=10, pady=10)  
  
task_listbox = tk.Listbox(root, width=50, height=10)  
task_listbox.grid(row=1, column=0, columnspan=3, padx=10, pady=10)  
  
complete_button = tk.Button(root, text="Complete", command=complete_task)  
complete_button.grid(row=2, column=0, padx=10, pady=10)  
  
delete_button = tk.Button(root, text="Delete", command=delete_task)  
delete_button.grid(row=2, column=1, padx=10, pady=10)  
  
# Update task list initially  
update_task_list()  
  
# Bind event to update selected task (currently not used but can be extended)  
def on_select(event):  
    pass  
task_listbox.bind("<<ListboxSelect>>", on_select)  
  
# Run the application  
root.mainloop()